package com.iwhalecloud.bss.kite.cucc.service.batch.attr;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Nullable;
import javax.annotation.PostConstruct;

import com.iwhalecloud.bss.pub.client.constanst.Symbols;
import org.assertj.core.util.Lists;
import org.springframework.stereotype.Component;

import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.service.batch.attr.processor.IBatchAttrProcessor;

import com.ztesoft.bss.common.util.SpringUtil;

/**
 * @author : xie.zhengjun
 * @className : BatchAttrProcessorFactory
 * @description :
 * @date : 2021/6/13 1:04
 */
@Component
public class BatchAttrProcessorFactory {
    private static final Map<String, IBatchAttrProcessor> PROCESSORS = new ConcurrentHashMap<>();

    @PostConstruct
    public void init() {
        Map<String, IBatchAttrProcessor> batchAttrProcessorMap = SpringUtil.getApplicationContext()
            .getBeansOfType(IBatchAttrProcessor.class);
        if (KiteMapUtils.isNotEmpty(batchAttrProcessorMap)) {
            batchAttrProcessorMap.forEach((beanName, bean) -> {
                Class<? extends IBatchAttrProcessor> clazz = bean.getClass();
                BatchAttrProcessor batchAttrProcessorAnno = clazz.getDeclaredAnnotation(BatchAttrProcessor.class);
                if (Objects.nonNull(batchAttrProcessorAnno)) {
                    String[] fieldNames = batchAttrProcessorAnno.fieldName();
                    String[] prodIds = batchAttrProcessorAnno.prodId();
                    if (fieldNames.length > 0) {
                        Arrays.stream(fieldNames).forEach(fieldName -> Arrays.stream(prodIds).forEach(
                            prodId -> PROCESSORS
                                .put(KiteStringUtils.join(fieldName, Symbols.UNDERLINE, prodId), bean)));
                    }
                }
            });
        }
    }

    @Nullable
    public IBatchAttrProcessor getBatchAttrProcessor(String fieldName, String prodId) {
        if (KiteStringUtils.isEmpty(fieldName)) {
            return null;
        }
        IBatchAttrProcessor batchAttrProcessor = PROCESSORS
            .get(KiteStringUtils.join(fieldName, Symbols.UNDERLINE, prodId));
        if (Objects.isNull(batchAttrProcessor)) {
            batchAttrProcessor = PROCESSORS.get(KiteStringUtils.join(fieldName, Symbols.UNDERLINE, "-1"));
        }
        return batchAttrProcessor;
    }
}
